package com.example.demo.conf;

import lombok.Data;
import org.apache.commons.lang3.Validate;

/**
 * <pre>
 *  描述: 存储文件的路径信息
 * </pre>
 *
 * @author godelgnis(wujiaer)
 * @version 1.0.0
 * @date 2022/3/10 19:59
 */
@Data
public class StorePath {
    /**
     * 组名
     */
    private String group;

    /**
     * 虚拟路径
     */
    private String remoteFileName;

    /**
     * 解析路径
     */
    private static final String SPLIT_GROUP_NAME_AND_FILENAME_SEPARATOR = "/";

    /**
     * group
     */
    private static final String SPLIT_GROUP_NAME = "group";


    /**
     * 存储文件路径
     */
    public StorePath() {
        super();
    }

    /**
     * 存储文件路径
     *
     * @param group 组名
     * @param remoteFileName 虚拟路径名
     */
    public StorePath(String group, String remoteFileName) {
        super();
        this.group = group;
        this.remoteFileName = remoteFileName;
    }


    /**
     * 获取文件全路径
     * @return 文件全路径
     */
    public String getFullPath() {
        return this.group.concat(SPLIT_GROUP_NAME_AND_FILENAME_SEPARATOR).concat(this.remoteFileName);
    }

    @Override
    public String toString() {
        return "StorePath [group=" + group + ", remoteFileName=" + remoteFileName + "]";
    }

    /**
     * 从Url当中解析存储路径对象
     *
     * @param filePath 有效的路径样式为(group/path) 或者
     *                 (http://ip/group/path),路径地址必须包含group
     * @return StorePath
     */
    public static StorePath parseFromUrl(String filePath) {
        Validate.notNull(filePath, "解析文件路径不能为空");

        String group = getGroupName(filePath);

        // 获取group起始位置
        int pathStartPos = filePath.indexOf(group) + group.length() + 1;
        String path = filePath.substring(pathStartPos);
        return new StorePath(group, path);
    }

    /**
     * 获取Group名称
     *
     * @param filePath 全路径名
     * @return 分组名
     */
    private static String getGroupName(String filePath) {
        //先分隔开路径
        String[] paths = filePath.split(SPLIT_GROUP_NAME_AND_FILENAME_SEPARATOR);
        if (paths.length == 1) {
            throw new IllegalStateException("解析文件路径错误,有效的路径样式为(group/path) 而当前解析路径为".concat(filePath));
        }
        for (String item : paths) {
            if (item.contains(SPLIT_GROUP_NAME)) {
                return item;
            }
        }
        throw new IllegalStateException("解析文件路径错误,被解析路径url没有group,当前解析路径为".concat(filePath));
    }


}
